package com.yangrong.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionCommunication {

	public static void main(String[] args) {
		final Business business = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 10; i++) {
					business.sub1(i);
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 10; i++) {
					business.sub2(i);
				}
			}
		}).start();

		for (int i = 1; i <= 10; i++) {
			business.main(i);
		}
	}

	static class Business {
		Lock lock = new ReentrantLock();
		Condition condition0 = lock.newCondition();
		Condition condition1 = lock.newCondition();
		Condition condition2 = lock.newCondition();
		private int isShouldSub = 0;

		public void sub2(int i) {
			lock.lock();
			try {
				// while 循环判断防止虚假唤醒
				while (isShouldSub != 2) {
					try {
						condition2.await();
//						this.wait();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				for (int j = 1; j <= 5; j++) {
					System.out.println("sub2 thread sequence of " + j + ", loop of " + i);
				}

				isShouldSub = 0;
				condition0.signal();
//				this.notify();
			} finally {
				lock.unlock();
			}
		}

		public void sub1(int i) {
			lock.lock();
			try {
				// while 循环判断防止虚假唤醒
				while (isShouldSub != 1) {
					try {
						condition1.await();
//						this.wait();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				for (int j = 1; j <= 5; j++) {
					System.out.println("sub1 thread sequence of " + j + ", loop of " + i);
				}

				isShouldSub = 2;
				condition2.signal();
//				this.notify();
			} finally {
				lock.unlock();
			}
		}

		public void main(int i) {
			lock.lock();
			try {
				while (isShouldSub != 0) {
					try {
						condition0.await();
//						this.wait();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				for (int j = 1; j <= 10; j++) {
					System.out.println("main thread sequence of " + j + ", loop of " + i);
				}

				isShouldSub = 1;
				condition1.signal();
//				this.notify();
			} finally {
				lock.unlock();
			}
		}
	}
}